#include <iostream>
#include <cstring>
#include <time.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <unistd.h>
#include <netinet/in.h>

#define PORT 8081

//    ./udp_server port
void Usage(std::string proc)
{
  std::cerr << "Usage: " << "\n\t" << proc << "local_port" << std::endl;
}

int main(int argc, char *argv[])
{
  if(argc != 2)
  {
    Usage(argv[0]);
    return 1;
  }

  int sock = socket(AF_INET, SOCK_DGRAM, 0);
  if(sock < 0)
  {
    std::cerr << "socket error" << std::endl;
    return 2;
  }
  std::cout << "sock: " << sock << std::endl;
  
  struct sockaddr_in local;
  memset(&local, 0, sizeof(local));
  local.sin_family = AF_INET;   //协议家族
  local.sin_port = htons(atoi(argv[1]));   //后续网络端口，会以源端口的方式，发送给对面
  local.sin_addr.s_addr = htonl(INADDR_ANY);

  if(bind(sock, (struct sockaddr*)&local, sizeof(local)) < 0)
  {
    std::cerr << "bind error" << std::endl;
    return 3;
  }

  char message[1024];
  for( ; ; )
  {
    memset(message, 0, sizeof(message));
    struct sockaddr_in peer;
    socklen_t len = sizeof(peer);
    ssize_t s = recvfrom(sock, message, sizeof(message) - 1, 0, (struct sockaddr*)&peer, &len);
    if(s > 0)
    {
      //接收命令行命令 command ls -a -l -i
      FILE *in = popen(message, "r");
      if(in == nullptr)
      {
        continue;
      }
      
      std::string echo_message;
      char line[128];
      while(fgets(line, sizeof(line), in))
      {
        echo_message += line;
      }
      sendto(sock, echo_message.c_str(), echo_message.size(), 0, (struct sockaddr*)&peer, len);
      //char *command[64] = {0};
      //command[0] = strtok(message, " ");
      //int i = 1;
      //while(command[i] = strtok(NULL, " "))
      //{
      //  i++;
      //}

      //if(fork() == 0)
      //{
      //  dup2(sock, 1);
      //  execvp(command[0], command);
      //  std::cerr << "client message# " << message << std::endl;
      //  exit(4);
      //}
      //sendto(sock, command[0], strlen(command[0]), 0, (struct sockaddr*)&peer, len);
    }
    else 
    {
      //TODO
    }
  }

  close(sock);
  return 0;
}
